#include "chatbubble.h"

ChatBubble::ChatBubble(Message msg, bool isSender, QWidget* parent)
    : QWidget(parent), msg(msg), isSender(isSender)
{
    // 区分发送方和接收方
    if (isSender) {
        color = QColor(144, 238, 144);
        mg = QMarginsF(12, 10, 15, 10);
    }
    else {
        color = QColor(234, 234, 234);
        mg = QMarginsF(15, 10, 12, 10);
    }

    //    QPalette pal(palette());
    //    pal.setColor(QPalette::Window, color);

        // 设置边框
    QVBoxLayout* layout = new QVBoxLayout(this);
    layout->setContentsMargins(mg.left(), mg.top(), mg.right(), mg.bottom());
    // 文本的设置
    QLabel* txt = new QLabel(msg.msg, this);
    //    txt->setGeometry(QRect(25, 2, 75, 35));
    txt->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);  // 设置大小策略
    txt->setAlignment(Qt::AlignTop | Qt::AlignLeft);  // 设置对齐方式
    txt->setWordWrap(true);
    txt->setOpenExternalLinks(true);
    // 消息框大小
    txt->setMaximumWidth(300);
    txt->adjustSize();

    // 字体
    QFontMetrics font(txt->font());
    //    QSize size(font.width(msg.msg), font.height());
    QSize size(txt->width(), txt->height());

    setMinimumSize(size.width() + mg.left() + mg.right(),
        size.height() + mg.top() + mg.bottom());

    layout->addWidget(txt);

}

void ChatBubble::paintEvent(QPaintEvent* event) {
    Q_UNUSED(event);

    if (!msg.msg.isEmpty()) {
        QPainter painter(this);
        painter.setRenderHint(QPainter::Antialiasing);

        QPainterPath path;

        path.addRoundedRect(rect(), mg.left(), mg.top());
        QPen pen(color);
        QBrush brush(color);

        painter.setPen(pen);
        painter.setBrush(brush);
        painter.drawPath(path.simplified());
    }
}
